<template>
  <view class="project-info-box" :class="{ readonly: !canEdit }">
    <view class="card-item summary">
      <view class="project-info">
        <view class="info-content">
          <view class="item-line">
            {{ projectAddress }}
          </view>
          <view class="item-line two">
            <view class="line-item">
              <view class="item-label">网关编号：</view>
              {{ gatewayNumber }}
            </view>
            <view class="line-item">
              <view class="item-label">安装日期：</view>
              {{ setupTime }}
            </view>
          </view>
        </view>
        <view v-if="canEdit" class="edit" @click="toEditProject">
          <view class="iconfont icon-editor"></view>
          <view class="edit-text">编辑</view>
        </view>
      </view>
      <view class="lamp-info">
        <view class="detail-item info">
          <view class="item-icon iconfont icon-lamp"></view>
          <view class="item-desc">灯具总数</view>
          <view class="item-count">{{ lampTotalCount }}</view>
        </view>
        <view class="detail-item danger">
          <view class="item-icon iconfont icon-warning"></view>
          <view class="item-desc">故障数量</view>
          <view class="item-count">{{ lampWarningCount }}</view>
        </view>
        <view class="detail-item info">
          <view class="item-icon iconfont icon-lighting"></view>
          <view class="item-desc">累计用电(Kwh)</view>
          <view class="item-count">{{ powerTotal }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-recycle"></view>
          <view class="item-desc">节能率(%)</view>
          <view class="item-count">{{ savingRate }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-leaf"></view>
          <view class="item-desc">累计降碳(T)</view>
          <view class="item-count">{{ carbonReduction }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-lighting"></view>
          <view class="item-desc">累计节电(Kwh)</view>
          <view class="item-count">{{ powerSaving }}</view>
        </view>
      </view>
      <view class="saving-info">
        <view class="price">
          <view class="item-label">电费单价：</view>
          {{ price }}元/度
        </view>
        <view class="saving-box">
          <view class="saving-item">
            累计节约电费：
            <view class="number">{{ moneySave }}</view>
          </view>
          <view class="saving-item">
            累计CO
            <view class="sub">2</view>
            减排：
            <view class="number">{{ carbonReduction }}吨</view>
          </view>
        </view>
      </view>
    </view>
    <view class="card-item energy-chart">
      <view class="section-title">
        <view class="title">能耗详情</view>
        <view class="title-tab"></view>
      </view>
      <view class="chart"><qiun-data-charts type="mix" :tapLegend="false" :opts="chartOptions" :chartData="chartData" /></view>
    </view>
    <view class="card-item demo-box">
      <view class="section-title">
        <view class="title">效果展示</view>
        <view v-if="canEdit && demoList.length" class="operate-box">
          <view class="operate-item" @click="toggleDemoEdit()">{{ isEditDemo ? '取消' : '编辑' }}</view>
        </view>
      </view>
      <view v-for="item in demoList" :key="item.key" class="demo-item">
        <cover-view v-if="isEditDemo && !isShowDeleteDemoDialog" class="delete-file" @click="deleteDemo(item)">X</cover-view>
        <video v-if="item.type === FILE_TYPE.VIDEO" class="demo-media video" :src="item.src"></video>
        <image v-if="item.type === FILE_TYPE.IMAGE" @click="previewImg(item)" class="demo-media image" :src="item.src" mode="aspectFill"></image>
        <view class="item-desc">{{ item.desc }}</view>
      </view>
    </view>
    <cover-view v-if="canEdit" class="page-bottom-btn" @click="toDemoAdd">新增效果展示</cover-view>

    <uni-popup ref="deleteDemoDialog" type="dialog" @change="onDeleteDemoChange($event)">
      <uni-popup-dialog type="info" cancelText="否" confirmText="是" :content="`确定要删除该展示？`" @confirm="doDeleteDemo()"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { getEnergyPointTimeText } from '@/utils/index.js'
import { PROJECT_TAB, FILE_TYPE } from '@/constant/index.js'
import color from '@/envs/_/variables.scss'
export default {
  props: {
    projectInfo: {
      type: Object
    }
  },
  computed: {
    canEdit() {
      return this.projectInfo.canEdit
    }
  },
  watch: {
    projectInfo() {
      this.initData()
    }
  },
  data() {
    return {
      gatewayNumber: '',
      projectAddress: '',
      ownerName: '',
      setupTime: '',
      lampTotalCount: 0,
      lampWarningCount: 0,
      powerTotal: 0,
      powerSaving: 0,
      savingRate: 0,
      carbonReduction: 0,
      price: 0,
      moneySave: 0,
      chartOptions: {
        color: [color.borderDark, color.success, color.primary],
        padding: [15, 10, 0, 5],
        legend: {},
        dataLabel: false,
        dataPointShape: false,
        xAxis: {
          disableGrid: true,
          boundaryGap: 'justify',
          labelCount: 13
        },
        yAxis: {
          gridType: 'dash',
          dashLength: 2,
          showTitle: true,
          data: [
            {
              min: 0,
              title: 'W',
              tofix: 0,
              unit: ''
            }
          ]
        },
        extra: {
          mix: {
            area: {
              opacity: 1
            },
            column: {
              width: 2
            }
          }
        }
      },
      chartData: {},
      chartRefreshInterval: 0,
      demoList: [],
      isEditDemo: false,
      isShowDeleteDemoDialog: false,
      targetDeleteDemoKey: null,
      FILE_TYPE
    }
  },
  mounted() {
    this.initData()
  },
  beforeDestroy() {
    clearInterval(this.chartRefreshInterval)
  },
  methods: {
    initData() {
      const self = this
      clearInterval(self.chartRefreshInterval)
      self.chartRefreshInterval = setInterval(self.refreshEnergyDetail, 300000)
      if (self.projectInfo?.id) {
        self.gatewayNumber = self.projectInfo.gatewayNumber || ''
        self.projectAddress = self.projectInfo.projectAddress || ''
        self.ownerName = self.projectInfo.projectAdminName || ''
        self.setupTime = self.projectInfo.setupTime
        self.lampTotalCount = self.projectInfo.lampTotalCount
        self.lampWarningCount = self.projectInfo.lampWarningCount
        self.powerTotal = self.projectInfo.powerTotal
        self.powerSaving = self.projectInfo.powerSaving
        self.savingRate = self.projectInfo.savingRate
        self.carbonReduction = self.projectInfo.carbonReduction
        self.price = self.projectInfo.price
        self.moneySave = self.projectInfo.moneySave
        self.demoList = self.projectInfo.demoList
        if (!self.demoList.length) {
          self.isEditDemo = false
        }
        self.getEnergyDetail()
      }
    },
    getEnergyDetail() {
      const self = this
      uni.request({
        url: '/project/day_vals',
        method: 'POST',
        data: {
          id: self.projectInfo.gateway_id
        },
        success(result) {
          if (result.data.success && result.data.data) {
            let { yesterday, today } = result.data.data
            if (!Array.isArray(yesterday) || !Array.isArray(today)) {
              console.log('能耗数据错误')
              return
            }
            const max = Math.max(...[].concat(yesterday).concat(today))
            const categories = Array.from(new Array(144), (item, index) => Math.ceil(index / 6))
            yesterday = Array.from(yesterday, item => (item ? item : null))
            today = Array.from(today, item => (item ? item : null))
            const splitIndex = today.findIndex(item => item === null)
            const splitLine = new Array(144)
            const splitText = getEnergyPointTimeText(splitIndex)
            splitLine[splitIndex] = Math.ceil(max * 1.2)
            self.chartData = {
              categories,
              series: [
                {
                  name: '昨天',
                  type: 'area',
                  style: 'curve',
                  data: yesterday,
                  color: color.borderDark,
                  addLine: true
                },
                {
                  name: '今天',
                  type: 'area',
                  style: 'curve',
                  data: today,
                  color: color.success,
                  addLine: true
                },
                {
                  name: splitText,
                  type: 'column',
                  color: color.primary,
                  data: splitLine
                }
              ]
            }
            console.log('图表数据：', JSON.stringify(self.chartData))
          }
        }
      })
    },
    refreshEnergyDetail() {
      const self = this
      const pages = getCurrentPages()
      const currPage = pages[pages.length - 1]
      if (currPage.$vm.activeTab === PROJECT_TAB.INFO) {
        self.getEnergyDetail()
      }
    },
    previewImg(item) {
      uni.previewImage({
        urls: [item.src]
      })
    },
    toggleDemoEdit() {
      this.isEditDemo = !this.isEditDemo
    },
    deleteDemo(target) {
      this.targetDeleteDemoKey = target.key
      this.$refs.deleteDemoDialog.open()
    },
    onDeleteDemoChange(option) {
      this.isShowDeleteDemoDialog = option.show
    },
    doDeleteDemo() {
      const self = this
      const demoData = Array.from(self.demoList.filter(item => item.key !== self.targetDeleteDemoKey), item => {
        return {
          key: item.key,
          type: item.type,
          path: item.path,
          desc: item.desc
        }
      })
      uni.request({
        url: '/project/modify',
        method: 'POST',
        data: {
          id: self.projectInfo.id,
          imgs: JSON.stringify(demoData)
        },
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'success',
              title: '保存成功'
            })
            self.$emit('refresh')
          }
        }
      })
    },
    toEditProject() {
      const self = this
      uni.navigateTo({
        url: `/pages/project-detail/edit-project/edit-project?id=${self.projectInfo.id}`
      })
    },
    toDemoAdd() {
      const self = this
      if (self.demoList.length >= 9) {
        uni.showToast({
          icon: 'none',
          title: '最多添加9个'
        })
        return
      }
      uni.navigateTo({
        url: `/pages/project-detail/add-demo/add-demo?id=${self.projectInfo.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.card-item {
  border-radius: 10rpx;
  background-color: $white;
}

.item-label {
  color: $text-secondary;
}
.summary {
  .project-info {
    padding: 30rpx;
    border-bottom: 2rpx solid $border-base;
    display: flex;
    justify-content: space-between;
    .info-content {
      width: 570rpx;
      .item-line {
        color: $text-base;
        font-size: $font-size-1;
        display: flex;
        align-items: center;
        &.two {
          margin-top: 20rpx;
          .line-item {
            &:first-child {
              margin-left: 0;
            }
            display: flex;
            align-items: center;
            margin-left: 40rpx;
          }
        }
      }
    }
    .edit {
      text-align: center;
      color: $primary;
      .iconfont {
        font-size: 40rpx;
      }
      .edit-text {
        font-size: $font-size-1;
      }
    }
  }
  .lamp-info {
    background-color: $background-light;
    display: flex;
    flex-wrap: wrap;
    border-bottom: 2rpx solid $border-base;
    .detail-item {
      text-align: center;
      border-right: 2rpx solid $border-lighter;
      padding-top: 28rpx;
      &:nth-child(3n) {
        border-right-color: transparent;
      }
      &:nth-child(n + 4) {
        border-top: 2rpx solid $border-light;
      }
      width: 230rpx;
      height: 172rpx;
      &.info {
        color: $info;
      }
      &.danger {
        color: $danger;
      }
      &.success {
        color: $success;
      }
      .item-icon {
        font-size: 44rpx;
      }
      .item-desc {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 6rpx;
        font-size: $font-size-1;
        .iconfont {
          margin-left: 10rpx;
        }
      }
      .item-count {
        font-size: $font-size-5;
        font-weight: bold;
      }
    }
  }
  .saving-info {
    padding: 30rpx;
    font-size: $font-size-1;
    .price {
      display: flex;
      align-items: center;
      justify-content: center;
      .item-label {
        color: $text-base;
      }
      .iconfont {
        margin-left: 10rpx;
      }
    }
    .saving-box {
      margin-top: 14rpx;
      position: relative;
      border-radius: 10rpx;
      height: 60rpx;
      padding: 0 40rpx;
      background-color: $background-base;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &:before {
        content: ' ';
        position: absolute;
        top: -8rpx;
        left: 307rpx;
        width: 0;
        height: 0;
        border-bottom: 8rpx solid $background-base;
        border-left: 17rpx solid transparent;
        border-right: 17rpx solid transparent;
      }
      .saving-item {
        display: flex;
        align-items: baseline;
      }
      .sub {
        font-size: $font-size-0;
        vertical-align: text-bottom;
      }
      .number {
        margin-left: 4rpx;
        font-weight: bold;
        color: $primary;
      }
    }
  }
}
.section-title {
  display: flex;
  justify-content: space-between;
  .title {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 20rpx;
    font-size: $font-size-3;
    font-weight: bold;
    &:before {
      position: absolute;
      left: 0;
      display: block;
      content: ' ';
      width: 6rpx;
      height: 30rpx;
      background-color: $primary;
      border-radius: 4rpx;
    }
  }
  .operate-box {
    display: flex;
    align-items: center;
    font-size: $font-size-2;
    color: $primary;
  }
}
.energy-chart {
  margin-top: 20rpx;
  padding: 30rpx;
  .section-title {
    margin-bottom: 10rpx;
  }
}
.demo-box {
  margin-top: 20rpx;
  padding: 30rpx;
  .demo-item {
    margin-top: 40rpx;
    position: relative;
    .delete-file {
      z-index: 2;
      position: absolute;
      border-radius: 50%;
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
      top: -20rpx;
      right: -20rpx;
      color: $white;
      background-color: $danger;
      font-size: $font-size-3;
      &:after {
        content: '';
        display: block;
        position: absolute;
        left: -10rpx;
        right: -10rpx;
        top: -10rpx;
        bottom: -10rpx;
      }
    }
    .demo-media {
      border-radius: 10rpx;
      width: 100%;
      height: 420rpx;
    }
    .desc {
      margin-top: 20rpx;
      font-size: $font-size-2;
    }
  }
}
</style>
